package com.example.rabbitextensionsdemo.listener;

import com.example.rabbitextensionsdemo.constant.Constants;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class AckListener {

    /**
     *  auto 自动确认
     *  不出现异常,正常确认
     *  出现异常, 消息就返回到队列中
     */
//    @RabbitListener(queues = Constants.ACK_QUEUE)
//    public void ackListener(Message message) {
//        Long deliveryTag = message.getMessageProperties().getDeliveryTag();
//        System.out.printf("[%s]接收到消息: %s, deliveryTag: %s\n",Constants.ACK_QUEUE,new String(message.getBody()),deliveryTag);
////        int num = 3/0;
//    }

    /**
     *  none 确认
     *  消费者接受到消息后,不论是消费成功还是消费失败,都进行确认
     */
//    @RabbitListener(queues = Constants.ACK_QUEUE)
//    public void ackListener(Mesxsage message) {
//        Long deliveryTag = message.getMessageProperties().getDeliveryTag();
//        System.out.printf("[%s]接收到消息: %s, deliveryTag: %s\n",Constants.ACK_QUEUE,new String(message.getBody()),deliveryTag);
////        int num = 3/0;
//    }
    /**
     *  manual 手动确认
     *  如果不手动确认,会一直挂起
     *  调用ack, 确认
     *  调用nack, 失败确认, 可以选择是否重新入队, 否则就丢掉消息
     */
    @RabbitListener(queues = Constants.ACK_QUEUE)
    public void ackListener(Message message, Channel channel) throws Exception{
        Long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            System.out.printf("[%s]接收到消息: %s, deliveryTag: %s\n",Constants.ACK_QUEUE,new String(message.getBody()),deliveryTag);
            System.out.println("处理业务逻辑");
//            int num = 3/0;
            // basicAck (deliveryTag, 是否批量确认)
            channel.basicAck(deliveryTag,false);
        }catch (Exception e) {
            // basicNack (deliveryTag, 是否批量确认, 是否打回到队列中)
            channel.basicNack(deliveryTag,true,false);
        }
    }
    // 重传机制
    @RabbitListener(queues = Constants.RETRY_QUEUE)
    public void retryListener(Message message) {
        MessageProperties messageProperties = message.getMessageProperties();
        long deliveryTag = messageProperties.getDeliveryTag();
        System.out.printf("[%s] 接受到消息: %s , deliveryTag: %s \n", Constants.ACK_QUEUE,new String(message.getBody()), deliveryTag);
        int num = 3/0;
    }

}
